// 角色管理
Ext.extend(CQCIS.module, {
    init: function() {
    	var listMeta = [{
			field: 'roleId',
            desc: '角色ID',
            width: 50
		}, {
            field: 'roleName',
            desc: '角色名称',
            width: 100
        }, {
            field: 'roleType',
            desc: '角色类型',
            renderer: function(value) {
            	switch(value) {
            		case '1':
            		return '系统角色';
            		case '2':
                    return '网站角色';
            	}
            	
            	return value;
            },
            width: 100
        }, {
            field: 'roleDesc',
            desc: '角色描述',
            width: 100
        }, {
            field: 'state',
            desc: '状态',
            renderer: function(value) {
            	switch(value) {
            		case '1':
            		return "有效";
            		case '0':
            		return "无效";
            	}
            	
            	return value;
            },
            width: 100
        }];
        
        // 增加，修改页面列表
        var roleMeta = [{
            name: 'roleId',
            fieldLabel: 'ID',
            xtype: 'hidden'
        }, {
            name: 'roleName',
            fieldLabel: '角色名称',
            allowBlank: false,
            regex: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            regexText: '角色名称只能由中文、英文或数字组成'
        }, {
            name: 'roleType',
            fieldLabel: '角色类型',
            allowBlank: false,
            store: [['1', '系统角色'], ['2', '网站角色']],
            triggerAction: 'all',
            editable: false,
            xtype: 'combo',
            value: '1'
        }, {
            name: 'roleDesc',
            fieldLabel: '角色描述'
        }, {
            name: 'state',
            fieldLabel: '状态',
            store: [['1', '有效'], ['0', '无效']],
            triggerAction: 'all',
            //mode: 'local',
            editable: false,
            xtype: 'combo',
            value: '1'
        }];
        
        // 组织信息窗口
        var roleWin = new CQCIS.Window({
            id: 'sm_role_win',
            title: '组织信息',
            height: 200,
            width: 380,
            items: new CQCIS.form.DWRForm({
                dwr: {
                    save: roleDwr.createRole,
                    load: roleDwr.getRole,
                    update: roleDwr.updateRole
                },
                labelWidth: 100,
                items: roleMeta,
                afterSubmit: function() {
                    grid.refresh();
                }
            })
        });
        
        // 工具栏增加按钮
        var addBtn = new Ext.Toolbar.Button({
            text: '增加',
            iconCls: 'btn_insert',
            handler: function() {
                roleWin.show();
            }
        });
        
        // 工具栏修改按钮
        var editBtn = new Ext.Toolbar.Button({
            text: '修改',
            iconCls: 'btn_modify',
            handler: function() {
                var region = grid.getSelectedRow();
                if (region) {
                    roleWin.load(region.roleId);
                } else {
                    CQCIS.msg('请选择要修改的记录!');
                }
            }
        });
        
        // 工具栏删除按钮
        var delBtn = new Ext.Toolbar.Button({
            text: '删除',
            iconCls: 'btn_config',
            handler: function() {
                var region = grid.getSelectedRow();
                if (region) {
                    Ext.Msg.confirm('操作提示', '确定要删除选择的角色，角色删除后将无法恢复?', function(param) {
                        if (param == 'yes') {
                            roleDwr.deleteRole(region.roleId, function() {
                                CQCIS.msg("选定的记录操作成功!");
                                grid.refresh();
                            });
                        }
                    });
                } else {
                    CQCIS.msg("请选择要操作的记录!");
                }
            }
        });
        
        // 关联窗口
        var roleFuncWin = new CQCIS.Window({
            id: 'sm_role_rela_func_win',
            title: '角色关联权限',
            width: 530,
            height: 400,
            items: new CQCIS.tree.ColumnTree({
                id: 'sm_roleman_roletree',
                rootId: '-1',
                rootText: '菜单权限',
                dwrCall: funcDwr.getSubFuncs,
                columns: [{
                    id: 'funcId',
                    header: '权限名称',
                    width: 280,
                    dataIndex: 'funcName'
                }, {
                    header: '权限类型',
                    width: 120,
                    dataIndex: 'funcType',
                    renderer: function(value) {
                        var str = "";
                        switch (value) {
                            case 1:
                                str = "系统权限";
                                break;
                            case 2:
                                str = "网站权限";
                                break;
                        }
                        return str;
                    }
                }, {
                    header: '资源类型',
                    width: 80,
                    dataIndex: 'funcResoType',
                    renderer: function(value) {
                        var str = "";
                        switch (value) {
                            case 1:
                                str = "URL";
                                break;
                            case 2:
                                str = "控件";
                                break;
                        }
                        return str;
                    }
                }],
                listeners: {
                    'beforeload': function(node) {
                        if (node.isRoot) {
                            node.getUI().show();
                            node.ownerTree.loader.params = [-1];
                        } else {
                            node.ownerTree.loader.params = [node.id];
                        }
                    }
                }
            }),
            save: function() {
                var checkFunc = roleFuncWin.items.get(0).getSelectedRows(), funcIds = [];
                for (var i = 0; i < checkFunc.length; i++) {
                    if (checkFunc[i].funcId != '-1') {
                        funcIds.push({
                        	roleId: grid.getSelectedRow().roleId,
                        	funcId: checkFunc[i].funcId
                        });
                    }
                }
                
                roleDwr.getFuncsOfRole(grid.getSelectedRow().roleId, {
                	callback: function(lv) {
	                    var checkedRows = [];
	                    for (var i = 0; i < lv.length; i++) {
	                        checkedRows.push(lv[i]);
	                    }
	                    
	                    var newRoleFuncs = [];
	                    // 新加的
	                    for (var i = 0; i < funcIds.length; i ++) {
	                    	var nowFuncId = funcIds[i].funcId;
	                    	var has = false;
	                    	for (var j = 0; j < checkedRows.length; j ++) {
	                    		var checkFuncId = checkedRows[j].funcId;
	                    		if (checkFuncId == nowFuncId) {
	                    			has = true;
	                    		}
	                    	}
	                    	if (!has) { // 新加的
	                    		newRoleFuncs.push(funcIds[i]);
	                    	}
	                    }
	                    
	                    // 删除的
	                    var delRoleFunc = [];
	                    for (var i = 0; i < checkedRows.length; i ++) {
                            var checkFuncId = checkedRows[i].funcId;
                            var has = false;
                            for (var j = 0; j < funcIds.length; j ++) {
                                var nowFuncId = funcIds[j].funcId;
                                if (checkFuncId == nowFuncId) {
                                    has = true;
                                }
                            }
                            if (!has) { // 删除的
                                delRoleFunc.push(checkedRows[i]);
                            }
                        }
	                    	                    
	                    roleDwr.createRoleFuncs(newRoleFuncs, function() {
	                    	roleDwr.deleteRoleFuncs(delRoleFunc, function() {
	                    		CQCIS.msg("角色与权限关联成功!");
                                roleFuncWin.hide();
	                    	});
		                });
	                },
	                async: false
                });
                
                
            },
            listeners: {
                show: function(o) {
                    roleDwr.getFuncsOfRole(grid.getSelectedRow().roleId, function(lv) {
                        var checkedRows = []
                        for (var i = 0; i < lv.length; i++) {
                            checkedRows.push({
                                funcId: lv[i].funcId
                            });
                        }
                        o.items.get(0).checkedRows = checkedRows;
                        o.items.get(0).root.reload();
                    });
                }
            }
        });
        
        // 工具栏关联权限按钮
        var relaFuncBtn = new Ext.Toolbar.Button({
            text: '关联权限',
            iconCls: 'btn_config',
            handler: function() {
                var role = grid.getSelectedRow();
                if (role && role.roleId) {
                    roleFuncWin.show();
                } else {
                    CQCIS.msg("请选择要关联的记录!");
                }
            }
        });
        
        // 员工信息grid
        var grid = new CQCIS.grid.PageGrid({
            id: 'sm_role_grid',
            firstColumn: 'radio',
            dwr: {
                call: roleDwr.pageRoles
            },
            metas: listMeta,
            tbar: [addBtn, editBtn, delBtn, relaFuncBtn],
            initload: true,
            bbar: 'true'
        });
        
        // 定义关联销毁对象数组，避免内存泄漏
        this.main.associatedComp = [roleWin, roleFuncWin];
        // 定义页面主元素
        this.main.add(grid);
        // 布局更新
        this.main.doLayout();
    }
});